package com.peaksport.framework.uuid;

import java.io.Serializable;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

import com.peaksport.framework.base.entity.CoreBaseEntity;
import com.peaksport.framework.exception.PKDevException;
import com.peaksport.framework.util.PKPublicUtils;

/**
 * 
 * 根据entityType产生唯一的id值
 * 
 * @author jinbin_guo  2019年6月5日 下午4:40:05
 *
 */
public class PKIdentifierGenerator implements IdentifierGenerator {

	@Override
	public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
		if (object instanceof CoreBaseEntity) {
			PKEntityType entityType = ((CoreBaseEntity)object).getEntityType();
			if (entityType == null) throw PKDevException.throwException("实体类[%s]objectType不能为空.",object.getClass().getName()) ;
			String id = ((CoreBaseEntity)object).getId();
			if (!PKPublicUtils.isEmpty(id)) {
				PKEntityType tmpEntityType = null;
				try {
					tmpEntityType = PKUuid.read(id).getType();
				} catch (Exception ex) {
					throw PKDevException.throwException("解析实体[%s]对象id值[%s]异常:%s", object.getClass().getName(),id,ex.getMessage());
				}
				if (!PKPublicUtils.equals(tmpEntityType, entityType)) {
					throw PKDevException.throwException("实体[%s](%s)对象id值[%s](%s)不合法.",object.getClass().getName(),entityType.toString(),id,tmpEntityType.toString());
				}
				return id;
			}
			
			
			return PKUuid.create(entityType).toString();
		} else {
			throw PKDevException.throwException("实体类[%s]必须继承自CoreBaseEntity基础实体类.",object.getClass().getName()) ;
		}
	}	
}
